<template>
	<view class="content">
		<view class="wid90 mar bacFFF borRad20" style="height: 250rpx;">
			<view style="height: 40rpx;"></view>
			<view class="dis disJuC foSi25 coFFF fowe600">
				<view class="dis disAl borRad40" style="height: 53rpx;padding: 0 20rpx;background-color: #035DFF;">向{{gasstation.name}}支付金额</view>
			</view>
			<view class="dis disJuC mar-top40" style="align-items: flex-end;vertical-align: bottom;">
				<view class="foSi50 fowe600 mar-right20" style="line-height: 50rpx;">¥</view>
				<input type="digit" @input="moneyInput" v-model="money" placeholder="请输入要支付的金额"
				:style="'width:'+(money?String(money).length*10:150)+'px;max-width:80%'"/>
			</view>
		</view>
		<view class="mar-top20 wid90 mar bacFFF borRad20" style="padding: 20rpx 0;">
			<view class="wid90 mar fowe600" style="color: #000;">
				<view class="dis disAl disJuB hei80">
					<view class="foSi30">油品类型</view>
					<picker class="foSi25" @change="typeChange" :value="typeIndex" :range="typeList">
						<view class="dis disAl">
							<view v-if="typeIndex" class="mar-right10">{{typeList[typeIndex]}}</view>
							<view v-if="!typeIndex" class="mar-right10" style="color: #4B4A4A;">请选择油品类型</view>
							<uni-icons type="right" size="25rpx"></uni-icons>
						</view>
					</picker>
				</view>
				<view class="dis disAl disJuB hei80">
					<view class="foSi30">{{userInfo.level_name?userInfo.level_name:'青铜会员'}}</view>
					<view class="foSi25" style="color: #4B4A4A;">享会员折扣<span style="color: #035DFF;">{{vip_discount}}折</span> </view>
				</view>
				<view class="dis disAl disJuB hei80">
					<view class="foSi30">积分抵扣</view>
					<view class="foSi25" style="color: #4B4A4A;">最高可抵扣<span style="color: #035DFF;">{{integral}}积分</span> </view>
				</view>
				<view class="dis disAl disJuB hei80">
					<view class="foSi30">使用优惠券</view>
					<picker class="foSi25" @change="youhuiChange" :value="youhuiIndex" :range-key="'name'" :range="youhuiList">
						<view class="dis disAl">
							<view v-if="youhuiIndex" class="mar-right10">{{youhuiList[youhuiIndex].coupon.title}}</view>
							<view v-if="!youhuiIndex" class="mar-right10" style="color: #4B4A4A;">请选择优惠券</view>
							<uni-icons type="right" size="25rpx"></uni-icons>
						</view>
					</picker>
				</view>
			</view>
		</view>
		<view class="mar-top20 wid90 mar borRad20 bacFFF" style="padding: 20rpx 0;">
			<view class="wid90 mar">
				<view class="dis disAl disJuB hei80" @click="pay = 0">
					<view class="dis disAl">
						<image src="../../static/zhifu.png" style="width: 44rpx;height: 39rpx;"></image>
						<view class="mar-left20">微信支付</view>
					</view>
					<radio color="#2F54EB" :checked="pay == 0" style="transform:scale(0.7)"/>
				</view>
				<view v-if="balance_status != 0" class="dis disAl disJuB hei80" @click="pay = 1">
					<view class="dis disAl">
						<image src="../../static/yue1.png" style="width: 44rpx;height: 39rpx;"></image>
						<view class="mar-left20">余额支付</view>
					</view>
					<radio color="#2F54EB" :checked="pay == 1" style="transform:scale(0.7)"/>
				</view>
			</view>
		</view>
		<view class="foSi30 wid87 mar mar-top30" style="text-align: right;color: #4B4A4A;">
			<view>已优惠：{{discount_amount.toFixed(2)}}元</view>
			<view class="mar-top10">合计：{{pay_amount.toFixed(2)}}元 </view>
		</view>
		<view class="wid100 dis disJuC poAbs" style="bottom: 50rpx;">
			<view class="dis disAl disJuC borRad10 foSi40 coFFF" @click="dingyue"
				style="width: 480rpx;height: 84rpx;background-color: #035DFF;">立即支付</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: '',
				gasstation: '',
				timer: null,
				money: '',
				youhuiList: [],
				youhuiIndex: null,
				coupon_log_id: 0,
				coupon_money: 0,
				typeList: ['92#','95#','0#柴油','-35#柴油'],
				typeIndex: null,
				oil_type: '',
				unitprice: '',
				vip_discount: 0,
				pay: 0,
				integral: 0,
				pay_amount: 0,
				discount_amount: 0,
				pd: false,
				balance_status: 1,
				integralMoney: 0
			}
		},
		onLoad() {
		},
		onShow() {
			var that = this
			var jiaId = uni.getStorageSync('jiaId')
			if(jiaId){
				that.jiaId = jiaId
			}
			var userinfo = uni.getStorageSync('userinfo')
			if(!userinfo){
				that.getUserInfo()
			}else{
				that.chongzhi()
			}
		},
		methods: {
			getUserInfo() {
				var that = this;
				uni.request({
					url: that.global.url + '/api/qianyu_petrol/gasstation_userlogin',
					method: "GET",
					header: {
						'site-id': that.global.site_id //自定义请求头信息
					},
					data: {
						openid: uni.getStorageSync('openid')
					},
					success(res) {
						let result = res.data
						console.log(result)
						if (result.code == 1) {
							uni.setStorageSync('userinfo', result.data);
							uni.setStorageSync('token', result.data.token);
							that.chongzhi()
						}else{
							uni.switchTab({
								url: '/pages/wode/wode'
							})
						}
					}
				})
			},
			chongzhi(){
				var that = this
				that.youhuiIndex = null
				that.coupon_log_id = 0
				that.coupon_money = 0
				that.money = ''
				that.userInfo = ''
				that.typeIndex = null
				that.oil_type = ''
				that.unitprice = ''
				that.vip_discount = 0
				that.pay = 0
				that.integral = 0
				that.pay_amount = 0
				that.discount_amount = 0
				that.pd = false
				that.balance_status = 1
				that.integralMoney = 0
				that.pd = false
				that.getList()
				that.getUser()
				that.getIntegral()
				that.getPaymentInfo()
			},
			dingyue() {
				var that = this
				// 要检查的订阅id
				let id = uni.getStorageSync('tzId').payment_template
				let id1 = uni.getStorageSync('tzId').integral_variation_template
				let id2 = uni.getStorageSync('tzId').refund_template
				// 这里是获取下发权限地方，根据官方文档，可以根据  wx.getSetting() 的 withSubscriptions   这个参数获取用户是否打开订阅消息总开关。后面我们需要获取用户是否同意总是同意消息推送。所以这里要给它设置为true 。
				wx.getSetting({
					withSubscriptions: true, //  这里设置为true,下面才会返回mainSwitch
					success: function(res) {
						// 调起授权界面弹窗
						// if (res.subscriptionsSetting.mainSwitch) { // 用户打开了订阅消息总开关
						// 	if (res.subscriptionsSetting.itemSettings !=
						// 		null) { // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
						// 		that.zhifu()
						// 	} else {
								// 当用户没有点击 ’总是保持以上选择，不再询问‘  按钮。那每次执到这都会拉起授权弹窗
								wx.showModal({
									title: '提示',
									content: '请授权开通服务通知',
									showCancel: true,
									success: function(ress) {
										if (ress.confirm) {
											wx.requestSubscribeMessage({ // 调起消息订阅界面
												tmplIds: [id,id1,id2],
												success(res) {
													console.log('订阅消息 成功 ');
													console.log(res);
													that.zhifu()
												},
												fail(er) {
													console.log("订阅消息 失败 ");
													console.log(er);
													that.zhifu()
												}
											})
										}
									}
								})
						// 	}
						// } else {
						// 	console.log('订阅消息未开启')
						// 	that.zhifu()
						// }
					},
					fail: function(error) {
						console.log(error);
						that.zhifu()
					},
				})
			},
			zhifu(){
				let that = this
				var userinfo = uni.getStorageSync('userinfo')
				if(!userinfo.mobile){
					uni.navigateTo({
						url: '/pages/wode/install'
					})
					return;
				}
				if(that.pd){
					return;
				}
				if(that.money==''){
					uni.showToast({
						title: '请输入支付金额',
						icon: 'none',
						duration: 2000
					}) 
				}
				if(!that.typeIndex){
					uni.showToast({
						title: '请选择油类型',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				that.pd = true
				uni.showLoading({
					title:'支付中...'
				})
				uni.request({
					url: that.global.url + '/api/qianyu_petrol/gasstation_pay',
					method: 'POST',
					header: {
						'site-id': that.global.site_id,
						"token": uni.getStorageSync('token')
					},
					data: {
						type: that.pay,
						gas_station_id: that.jiaId,
						oil_type: that.oil_type,
						coupon_log_id: that.coupon_log_id,
						coupon_money: that.coupon_money.toFixed(2),
						vip_discount: that.userInfo.vip_discount,
						unitprice: that.unitprice,
						pay_amount: that.pay_amount.toFixed(2),
						total_amount: Number(that.money).toFixed(2),
						discount_amount: that.discount_amount.toFixed(2),
						pay_type: that.pay,
						point_deduction: that.integral,
						point_deduction_money: that.integralMoney
					},
					success: (res) => {
						let result = res.data
						console.log(result)
						if(that.pay == 1){
							if(result.code==1){
								uni.showModal({
									title: '提示',
									content: '支付成功',
									showCancel: false,
									success: function(res) {
										if (res.confirm) {
											setTimeout(function(){
												uni.navigateTo({
													url: '/pages/order/order',
												});	
											},1000)
										}
									}
								})
							}else{
								uni.showToast({
									title: '支付失败',
									icon: 'none',
									duration: 2000
								})
							}
						}else{
							uni.requestPayment({
								timeStamp: result.timeStamp,
								nonceStr: result.nonceStr,
								package: result.package,
								signType: 'MD5',
								paySign: result.paySign,
								success: function (res) {
									console.log(res);
									uni.showModal({
										title: '提示',
										content: '支付成功',
										showCancel: false,
										success: function(res) {
											if (res.confirm) {
												setTimeout(function(){
													uni.navigateTo({
														url: '/pages/order/order',
													});	
												},1000)
											}
										}
									})
								},
								fail: function (err) {
									console.log('fail:' + JSON.stringify(err));
										// 支付失败
									console.log(err)
									uni.showToast({
										title: '支付失败',
										icon: 'none',
										duration: 2000
									})
								}
							});
						}
					},
					complete() {
						uni.hideLoading()
						that.pd = false
					}
				});
			},
			moneyInput: function(event) {
				var that = this
				if (that.timer !== null) clearTimeout(that.timer)
				that.timer = setTimeout(() => {
					that.money = event.target.value
					console.log(that.money)
					that.youhuiList = []
					that.getCouponList()
					if(that.typeIndex){
						that.moneyS()
					}
				}, 1000)
			},
			moneyS(){
				// 折扣价格
				var moneyZ = this.money * (this.vip_discount / 10)
				this.integralMoney = 0
				if(this.userInfo.integral>0){
					// 自己拥有积分的可抵扣金额
					var deduction = this.deduction!=0?this.userInfo.integral / this.deduction:0
					//最大可使用积分抵扣的金额
					var percentage = this.money * (this.percentage / 100)
					console.log(deduction);
					console.log(percentage);
					if(percentage <= deduction){
						// 抵扣 最大可抵扣积分
						this.integral = Math.round(percentage * this.deduction)
						this.integralMoney = percentage
					}else{
						// 抵扣 自己所有积分
						this.integral = Math.round(deduction * this.deduction)
						this.integralMoney = deduction
					}
				}else{
					this.integral = 0
				}
				var pay_money = moneyZ - this.coupon_money - this.integralMoney
				if(pay_money <= 0){
					this.pay_amount = 0.01
					this.discount_amount = this.money - 0.01
				}else{
					this.pay_amount = pay_money
					this.discount_amount = this.money - this.pay_amount
				}
			},
			typeChange: function(e) {
				this.typeIndex = e.detail.value
				this.oil_type = this.typeIndex == 0?'ninety_two_oil':this.typeIndex == 1?'ninety_five_oil':this.typeIndex == 2?'zero_oil':'negative_thirty_five_oil'
				this.unitprice = this.typeIndex == 0?this.gasstation.ninety_two_oil:this.typeIndex == 1?this.gasstation.ninety_five_oil:
				this.typeIndex == 2?this.gasstation.zero_oil:this.gasstation.negative_thirty_five_oil
				this.vip_discount = this.typeIndex == 0?this.userInfo.ninety_two_oil:this.typeIndex == 1?this.userInfo.ninety_five_oil:
				this.typeIndex == 2?this.userInfo.zero_oil:this.userInfo.negative_thirty_five_oil
				if(this.money){
					this.moneyS()
				}
			},
			youhuiChange: function(e) {
				if(this.youhuiList.length > 0){
					// console.log(this.youhuiList[this.youhuiIndex].coupon.money);
					this.youhuiIndex = e.detail.value
					this.coupon_log_id = this.youhuiList[this.youhuiIndex].id
					this.coupon_money = this.youhuiList[this.youhuiIndex].coupon.money-0
					this.moneyS()
				}
			},
			getCouponList() {
				var that = this;
				uni.request({
					url: that.global.url + '/api/qianyu_petrol/gasstation_pay_coupon_list',
					method: "POST",
					header: {
						'site-id': that.global.site_id,//自定义请求头信息
						'token': uni.getStorageSync('token')
					},
					data: {
						'gas_station_id': uni.getStorageSync('jiaId'),
						'order_money': that.money
					},
					success(res) {
						let result = res.data
						console.log(result)
						if (result.code == 1) {
							that.youhuiIndex = 0
							var list = result.data
							for (var i = 0; i < list.length; i++) {
								list[i].name = list[i].coupon.title
							}
							console.log(list)
							that.youhuiList = list
						}
					}
				})
			},
			getPaymentInfo() {
				var that = this;
				uni.request({
					url: that.global.url + '/api/qianyu_petrol/gasstation_payment_info',
					method: "POST",
					header: {
						'site-id': that.global.site_id,//自定义请求头信息
						'token': uni.getStorageSync('token')
					},
					data: {},
					success(res) {
						let result = res.data
						console.log(result)
						if (result.code == 1) {
							that.balance_status = result.data.balance_status
						}
					}
				})
			},
			getIntegral() {
				var that = this;
				uni.request({
					url: that.global.url + '/api/qianyu_petrol/gasstation_information',
					method: "POST",
					header: {
						'site-id': that.global.site_id,//自定义请求头信息
						'token': uni.getStorageSync('token')
					},
					data: {},
					success(res) {
						let result = res.data
						console.log(result)
						if (result.code == 1) {
							that.percentage = result.data.percentage
							that.deduction = result.data.deduction
						}
					}
				})
			},
			getUser() {
				var that = this;
				uni.request({
					url: that.global.url + '/api/qianyu_petrol/gasstation_user_info',
					method: "POST",
					header: {
						'site-id': that.global.site_id//自定义请求头信息
					},
					data: {
						openid: uni.getStorageSync('openid')
					},
					success(res) {
						let result = res.data
						console.log(result)
						if (result.code == 1) {
							that.userInfo = result.data
						}
					}
				})
			},
			getList() {
				var that = this;
				uni.request({
					url: that.global.url + '/api/qianyu_petrol/gasstation_index',
					method: "POST",
					header: {
						'site-id': that.global.site_id, //自定义请求头信息
					},
					data: {
						id: that.jiaId
					},
					success(res) {
						let result = res.data
						console.log(result)
						if (result.code == 1) {
							that.gasstation = result.data
						}
					}
				})
			},
			tiaozhuan(url) {
				uni.navigateTo({
					url: url
				})
			}
		}
	}
</script>

<style>
	.content {
		background: linear-gradient(#E4F7FD 20%, #F8F9FD 80%);
		min-height: 100vh;
	}

</style>
